package com.product.android.utils.wbAtUtils;

import java.util.regex.Matcher;

import com.product.android.utils.MyPasteListener;
import com.product.android.utils.WbRegexUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.EditText;

/**
 * @ClassName WbAtView
 * @Function 微博At管理类
 * @Reason
 * 
 * @author HuangYK
 * @version v1.3.2
 * @Date 2013 2013-12-16 下午2:48:26
 * 
 * @see
 */
public class WbAtView {
	private EditText mEditText;

	private WbAtTextWatcher mWbAtTextWatcher;
	private MyPasteListener mPasteListener;

	public WbAtView(Context context, EditText editText) {
		mEditText = editText;

		mWbAtTextWatcher = new WbAtTextWatcher(context, mEditText);
		mPasteListener = new MyPasteListener(context);
		mWbAtTextWatcher.setPasteListener(mPasteListener);
		mEditText.addTextChangedListener(mWbAtTextWatcher);

		InputFilter[] curfilters = mEditText.getFilters();
		if (curfilters != null && curfilters.length > 0) {
			InputFilter[] newfilters = new InputFilter[curfilters.length + 1];
			newfilters[0] = mPasteListener;
			System.arraycopy(curfilters, 0, newfilters, 1, curfilters.length);
			mEditText.setFilters(newfilters);
		}
	}

	/**
	 * 拼凑<M>标签字符串
	 * 
	 * @n<b>函数名称</b> :getMTagString
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param name
	 * @param @param fid
	 * @param @return
	 * @return String
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16上午11:07:02
	 */
	public static String getMTagString(String name, long fid) {
		StringBuilder strMTag = new StringBuilder();
		strMTag.append(String.format("<M %d>@", fid)).append(name)
				.append(WbRegexUtils.M_TAG_STRING_END);
		return strMTag.toString();
	}

	/**
	 * 把单个<M>标签字符串转换成@用户名
	 * 
	 * @n<b>函数名称</b> :getAtString
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param strMTag
	 * @param @return
	 * @return String
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16下午8:48:34
	 */
	public static String getAtString(String strMTag) {
		int atStart = strMTag.indexOf("@");
		int atEnd = strMTag.indexOf(WbRegexUtils.M_TAG_STRING_END);
		try {
			return strMTag.substring(atStart, atEnd);
		} catch (StringIndexOutOfBoundsException e) {
			Log.e("WbAtView", "getAtString index out of bounds");
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 将含有<M>标签的微博内容转换成 只有@用户名的微博内容
	 * 
	 * @n<b>函数名称</b> :getOnlyAtContent
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param content
	 * @param @return
	 * @return String
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16上午11:06:51
	 */
	public static String getOnlyAtContent(String content) {
		if(TextUtils.isEmpty(content)){
			return "";
		}
		StringBuilder sbLocal = new StringBuilder(content);
		String strMTag;
		Matcher mcMTag = WbRegexUtils.AT_M_TAG_PATTERN.matcher(sbLocal);
		while (mcMTag.find()) {
			strMTag = mcMTag.group();
			sbLocal.replace(mcMTag.start(), mcMTag.end(), getAtString(strMTag));
			mcMTag = WbRegexUtils.AT_M_TAG_PATTERN.matcher(sbLocal);
		}
		String strOnlyAtContent = sbLocal.toString();
		sbLocal.reverse();
		return strOnlyAtContent;
	}

	/**
	 * 把<M>标签字符串转换为图片插入editText中
	 * 
	 * @n<b>函数名称</b> :insertAtName
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param context
	 * @param @param strMTag
	 * @param @param editText
	 * @return void
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16上午11:18:06
	 */
	public static void insertAtName(Context context, String strMTag,
			EditText editText) {
		if(TextUtils.isEmpty(strMTag))
			return;
		int textSize = (int) editText.getTextSize();
		String strAt = getOnlyAtContent(strMTag);	
		if(TextUtils.isEmpty(strAt))
			return;
		SpannableString spanAtName = new SpannableString(strMTag);
		AtImageSpan isAtName = new AtImageSpan(drawMTagBitmapDrawable(textSize,
				strAt), strMTag, ImageSpan.ALIGN_BOTTOM);
		spanAtName.setSpan(isAtName, 0, spanAtName.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		editText.getText().insert(editText.getSelectionStart(), spanAtName);
		editText.requestFocus();
	}

	/**
	 * 把加入的<M>标签转换成图片
	 * 
	 * @n<b>函数名称</b> :setSpanAtName
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param context
	 * @param @param editAble
	 * @param @param textSize
	 * @return void
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16上午11:06:35
	 */
	public static void setSpanAtName(Context context, Editable editAble,
			int textSize) {
		String strMTag;
		Matcher mcMTag = WbRegexUtils.AT_M_TAG_PATTERN.matcher(editAble
				.toString());
		while (mcMTag.find()) {
			strMTag = mcMTag.group();
			AtImageSpan isAtName = new AtImageSpan(drawMTagBitmapDrawable(
					textSize, getAtString(strMTag)), strMTag,
					ImageSpan.ALIGN_BOTTOM);
			editAble.setSpan(isAtName, mcMTag.start(), mcMTag.end(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}

	/**
	 * 把<M>标签中的@XXX画到bitmap上
	 * 
	 * @n<b>函数名称</b> :drawMBitmap
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param @param textSize
	 * @param @param text
	 * @param @param density
	 * @param @return
	 * @return Bitmap
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16上午11:28:16
	 */
	private static BitmapDrawable drawMTagBitmapDrawable(int textSize,
			String text) {
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setTextSize(textSize);
		
		Rect textBounds = new Rect();
		paint.getTextBounds(text, 0, text.length(), textBounds);
		
		Bitmap bitmap = Bitmap.createBitmap(
				(int) (textBounds.width() + 4),
				(int) (textBounds.height()+4), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		canvas.drawText(text, 0, (int)(textBounds.height() - 4), paint);
		canvas.save(Canvas.ALL_SAVE_FLAG);
		canvas.restore();
		canvas = null;
		BitmapDrawable bdSpan = new BitmapDrawable(bitmap);
		bdSpan.setBounds(0, 0, (int) (bitmap.getWidth()),
				(int) (bitmap.getHeight()));
		bitmap = null;
		return bdSpan;
	}

	/**
	 * 退出时回收At图片
	 * 
	 * @n<b>函数名称</b> :onDestroy
	 * @brief
	 * @see
	 * @version Ver 1.3.2
	 * @param
	 * @return void
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2013-12-16下午2:51:54
	 */
	public void onDestroy() {
		if (TextUtils.isEmpty(mEditText.getText()))
			return;
		AtImageSpan[] mImageSpan = mEditText.getEditableText().getSpans(0,
				mEditText.getText().length(), AtImageSpan.class);
		if (mImageSpan == null || mImageSpan.length == 0)
			return;
		Bitmap bitmap;
		for (AtImageSpan span : mImageSpan) {
			if (span.getDrawable() instanceof BitmapDrawable) {
				bitmap = ((BitmapDrawable) span.getDrawable()).getBitmap();
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
				}
			}
		}
	}
}
